package com.proj.springbootdemo.service;

import com.proj.springbootdemo.dao.mapper.gen.BooksMapper;
import com.proj.springbootdemo.dao.model.gen.Books;
import com.proj.springbootdemo.utils.Errors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author liujia
 */
@Service
public class DemoService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private BooksMapper booksMapper;

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Books getBook() {
        jdbcTemplate.execute("select * from books");

        Books b = booksMapper.selectByPrimaryKey(1);
        return b;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Books getBookExc() {
        Books b = Books.builder()
                .id(2222)
                .bookname("bookname2")
                .publisherid(2)
                .build();

        booksMapper.insert(b);

        if (true) {
            throw Errors.TESTERROR.exception();
        }

        return b;
    }
}
